package com.db.httpserver;

import java.io.IOException;
import java.util.concurrent.Callable;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

public class LoadTestRunner implements Callable<Result> {
    private int requests;
    
    public LoadTestRunner(int requests) {
        this.requests = requests;
    }

    @Override
    public Result call() {
        Result result = new Result();
        HttpClient client = new HttpClient();
        GetMethod getReuest = new GetMethod("http://localhost:8080");
        long duration = System.currentTimeMillis();
        int errors = 0;
        try {
            int status = 0;
            for (int i = 0; i < requests; ++i) {
                status = client.executeMethod(getReuest);
                if (HttpStatus.SC_OK != status)
                    errors++;
            }
        } catch (HttpException e) {
            errors++;
        } catch (IOException e) {
            errors++;
        }
        duration = System.currentTimeMillis() - duration;
        result.setRunTime(duration);
        result.setErrors(errors);
        return result;
    }

}
